package com.hzxy.yiyid.web.module.controller;

import com.hzxy.yiyid.web.common.base.BaseResult;
import com.hzxy.yiyid.web.common.constants.YiyidConstants;
import com.hzxy.yiyid.web.common.error.ErrorCodeEnum;
import com.hzxy.yiyid.web.module.controller.vo.DrugRequestVO;
import com.hzxy.yiyid.web.module.controller.vo.MedicineVO;
import com.hzxy.yiyid.web.module.controller.vo.SymptomVO;
import com.hzxy.yiyid.web.module.repository.MedicineDoRepository;
import com.hzxy.yiyid.web.module.repository.entity.MedicineDo;
import com.hzxy.yiyid.web.module.service.DrugService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DrugController
 * @Description 药品相关
 * @Author RAICOM2023
 * @Date 2023/3/6 22:31
 * @Version 1.0
 **/
@Api(tags = "药品相关接口")
@Controller
@RequestMapping(value = "/drug")
public class DrugController {

    private static final Logger logger = LoggerFactory.getLogger(DrugController.class);

    @Resource
    private DrugService drugService;

    @Resource
    private MedicineDoRepository medicineDoRepository;

    /*
     * @Author RAICOM2023
     * @Description //根据药品名称查询不合规药品
     * @Date 22:39 2023/3/6
     * @Param [drugRequestVO]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @ApiOperation(value = "获取不合标准药品列表",notes = "获取不合标准药品列表")
    @RequestMapping(value = "/getSubstandardDrugList", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<?> getSubstandardDrugList(@RequestBody DrugRequestVO drugRequestVO) {
        try{
            if(StringUtils.isBlank(drugRequestVO.getYpmc())){
                return BaseResult.fail(ErrorCodeEnum.DRUG_PARAM_NULL_ERROR.getErrorCode(),ErrorCodeEnum.DRUG_PARAM_NULL_ERROR.getMsg());
            }
            if (null == drugRequestVO.getPageNo()) {
                drugRequestVO.setPageNo(1);
            }
            if (null == drugRequestVO.getPageSize()) {
                drugRequestVO.setPageSize(20);
            }
            Map<String, Object> returnMap = new HashMap<>();
            List<Map<String, Object>> substandardDrugMapList =
                    drugService.listSubstandardDrug(drugRequestVO);
            long total = drugService.findSubstandardDrugTotal(drugRequestVO);
            returnMap.put("list", substandardDrugMapList);
            returnMap.put("total", total);
            return BaseResult.success(returnMap);
        }catch(Exception e){
            logger.error(ErrorCodeEnum.SYSTEM_ERROR.getMsg(),e);
            return BaseResult.error(ErrorCodeEnum.SYSTEM_ERROR.getErrorCode(),ErrorCodeEnum.SYSTEM_ERROR.getMsg());
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //医保药品
     * @Date 21:40 2023/3/6
     * @Param [drugRequestVO]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @ApiOperation(value = "获取药品列表 ",notes = "获取药品列表")
    @RequestMapping(value = "/getMedicareDrugList", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<?> getMedicareDrugList(@RequestBody DrugRequestVO drugRequestVO) {
        try{
            if(StringUtils.isBlank(drugRequestVO.getTym())){
                return BaseResult.fail(ErrorCodeEnum.DRUG_PARAM_NULL_ERROR.getErrorCode(),ErrorCodeEnum.DRUG_PARAM_NULL_ERROR.getMsg());
            }
            if (null == drugRequestVO.getPageNo()) {
                drugRequestVO.setPageNo(1);
            }
            if (null == drugRequestVO.getPageSize()) {
                drugRequestVO.setPageSize(20);
            }
            Map<String, Object> returnMap = new HashMap<>();
            List<Map<String, Object>> medicareDrugMapList =
                    drugService.listMedicareDrug(drugRequestVO);
            long total = drugService.findMedicareDrugTotal(drugRequestVO);
            returnMap.put("list", medicareDrugMapList);
            returnMap.put("total", total);
            return BaseResult.success(returnMap);
        }catch(Exception e){
            logger.error(ErrorCodeEnum.SYSTEM_ERROR.getMsg(),e);
            return BaseResult.error(ErrorCodeEnum.SYSTEM_ERROR.getErrorCode(),ErrorCodeEnum.SYSTEM_ERROR.getMsg());
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //识别药物说明书
     * @Date 13:02 2023/3/6
     * @Param [request]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @ApiOperation(value = "Ai分析药品",notes = "Ai分析药品")
    @RequestMapping(value = "/aiDrug", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<?> aiDrug(HttpServletRequest request) {
        try{
            if (!(request instanceof MultipartHttpServletRequest)) {
                return BaseResult.error(ErrorCodeEnum.REQUEST_TYPE_ERROR.getErrorCode(),ErrorCodeEnum.REQUEST_TYPE_ERROR.getMsg());
            }
            MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
            if ( null == file ) {
                return BaseResult.error(ErrorCodeEnum.UPLOAD_FILE_NULL_ERROR.getErrorCode(),ErrorCodeEnum.UPLOAD_FILE_NULL_ERROR.getMsg());
            }
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (null == suffixName || !suffixName.toLowerCase().matches(YiyidConstants.SUFFIX.IMAGE)) {
                return BaseResult.error(ErrorCodeEnum.UPLOAD_FILE_SUFFIX_ERROR.getErrorCode(),ErrorCodeEnum.UPLOAD_FILE_SUFFIX_ERROR.getMsg());
            }
            return drugService.aiDrug(file);
        }catch(Exception e) {
            logger.error(ErrorCodeEnum.SYSTEM_ERROR.getMsg(), e);
            return BaseResult.error(ErrorCodeEnum.SYSTEM_ERROR.getErrorCode(), ErrorCodeEnum.SYSTEM_ERROR.getMsg());
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //快速荐药-根据文本输入框输入的症状信息获得用药方案
     * @Date 8:28 2023/4/29
     * @Param [symptomVO]
     * @return com.hzxy.yiyi.web.common.base.BaseResult<?>
     **/
    @ApiOperation(value = "获取药物计划",notes = "获取药物计划")
    @RequestMapping(value = "/getMedicationPlan", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<?> getMedicationPlan(@RequestBody SymptomVO symptomVO) {
        try{
            if(StringUtils.isBlank(symptomVO.getSymptomText())){
                return BaseResult.fail(ErrorCodeEnum.MD_SYMPTOM_BLANK_ERROR.getErrorCode(),ErrorCodeEnum.MD_SYMPTOM_BLANK_ERROR.getMsg());
            }
            return drugService.getMedicationPlan(symptomVO.getSex(),symptomVO.getAgeGroup(),symptomVO.getSymptomText());
        }catch(Exception e){
            logger.error(ErrorCodeEnum.MD_SYSTEM_ERROR.getMsg(),e);
            return BaseResult.error(ErrorCodeEnum.MD_SYSTEM_ERROR.getErrorCode(),ErrorCodeEnum.MD_SYSTEM_ERROR.getMsg());
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //点击下载说明书
     * @Date 8:32 2023/5/5
     * @Param [medicineVO, request, response]
     * @return void
     **/
    @ApiOperation(value = "下载方向",notes = "下载方向")
    @RequestMapping(value = "/downloadDirections", method = RequestMethod.POST)
    @ResponseBody
    public void downloadDirections(@RequestBody MedicineVO medicineVO,
                                   HttpServletRequest request, HttpServletResponse response) {
        Long id = medicineVO.getMedicineId();
        if(id==null){
            logger.error("点击下载说明书-文本id为空");
            return;
        }
        OutputStream out = null;
        try {
            Document document = drugService.downloadDirections(id);
            if(document==null){
                logger.info("点击下载说明书-导出文件为空");
                return;
            }
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            out = response.getOutputStream();
            MedicineDo medicineDo = medicineDoRepository.findById(id).get();
            String fileName = URLEncoder.encode(medicineDo.getChineseName()+"-"+sdf.format(date)+".docx","UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            document.saveToStream(out, FileFormat.Docx);
        }catch (Exception e){
            logger.error("点击下载说明书-导出失败", e);
        }finally{
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("点击下载说明书-关闭流异常",e);
                }
            }
        }
    }
}
